package com.example.obs.utils;

import com.example.obs.model.domin.User;
import com.example.obs.vo.MyException;
import com.example.obs.vo.ResultVO;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author Kevin
 * @date 2020-09-23 15:35
 */
public class UserUtils {

    public static User getCurrentUser() {
        User currentUser = getCurrentUserNoException();
        if (currentUser == null) {
            throw new MyException(ResultVO.error(403, "尚未登录"));
        }
        return currentUser;
    }

    public static User getCurrentUserNoException() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof User) {
            return (User)principal;
        }
        return null;
    }

    public static Integer getCurrentUserDeparmentIdNoException() {
        User currentUser = getCurrentUserNoException();
        if (currentUser != null) {
            return currentUser.getDepartmentId();
        }
        return 0;
    }

}
